import Vue from 'vue'
import VueRouter from 'vue-router'

import { getToken } from '@/utils/token'
// 导入需要配置的页面
// @代表的就是src目录
// 如果某个目录下的文件名叫index.vue/index.js，那么只需导入文件夹，下面的index.vue和index.js都会默认补全
import login from '../views/login'
import layout from '../views/layout'
// 导入layout嵌套组件
import user from '@/views/layout/user'
import chart from '@/views/layout/chart'
import enterprise from '@/views/layout/enterprise'
import question from '@/views/layout/question'
import subject from '@/views/layout/subject'

// 学习父子组件传值
import father from '@/text/father/father.vue'
// 学习兄弟组件
import parent from '@/text/brother/parent.vue'
Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/layout',
    name: 'layout',
    component: layout,
    children: [
      {
        path: 'user',
        component: user

      },
      {
        path: 'chart',
        component: chart

      },
      {
        path: 'enterprise',
        component: enterprise

      },
      {
        path: 'question',
        component: question

      },
      {
        path: 'subject',
        component: subject

      }
    ]
  },
  // 学习父子组件传值
  {
    path: '/father',
    name: 'father',
    component: father
  },
  // 学习兄弟组件
  {
    path: '/parent',
    name: 'parent',
    component: parent
  }
]
const router = new VueRouter({
  routes
})

// to:从哪里来
// from到哪里去
// next()回调函数必须有,决定通过还是不通过,不通过跳回首页,缺失他无法到达
// 权限控制
// 初步判断是不是跳转到首页,在判断有无token
// 按需导入获取token在判断有token过,没有token跳回到登录页
router.beforeEach((to, from, next) => {
  console.log('到哪里去', to)
  // console.log('从哪里来', from)
  if (to.path === '/login') {
    next()
  } else {
    // 获取token
    console.log('token')
    const token = getToken()
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
